const Router = require("koa-router");
const { Auth } = require("@middlewares/auth");
const { Favor } = require("@models/favor");
const { User } = require("@models/user");
const { News } = require("@models/news");


const router = new Router({
  prefix: "/v1/user/favor",
});

fav_num = async (news_id) => {
  const count_num = await Favor.count({
    where: {
      news_id,
    },
  });

  await News.update(
    { fav_num: count_num },
    {
      where: {
        news_id,
      },
    }
  );
};

// 我的收藏列表
router.post("/list", new Auth().m, async (ctx) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = {
    uid: ctx.auth.uid,
  };
  const { count: total, rows } = await Favor.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    include: [
      {
        model: News,
        attributes: { exclude: ["content"] },
        where: { is_del: true },
      },
    ],
  });

  ctx.body = {
    code: 200,
    msg: "查询成功",
    total,
    data: rows,
  };
});

// 是否收藏
router.post("/is_favor", new Auth().m, async (ctx) => {
  const { news_id } = ctx.request.body;
  const favor = await Favor.findOne({
    where: { uid: ctx.auth.uid, news_id },
    raw: true,
  });

  ctx.body = { code: 200, msg: "查询成功", data: favor ? true : false };
});

// 取消收藏
router.post("/cancel", new Auth().m, async (ctx) => {
  const { news_id } = ctx.request.body;
  const fav = await Favor.destroy({
    where: { news_id, uid: ctx.auth.uid },
    force: true,
  });
  if (!fav) {
    global.errs.AuthFailed("取消收藏失败");
  }
  fav_num(news_id);
  ctx.body = { code: 200, msg: "取消收藏成功" };
});

// 添加收藏
router.post("/add", new Auth().m, async (ctx) => {
  const { news_id } = ctx.request.body;
  const fav = await Favor.findOne({
    where: { uid: ctx.auth.uid, news_id },
  });
  if (fav) {
    global.errs.AuthFailed("已收藏");
  }
  const news = await Favor.create({ uid: ctx.auth.uid, news_id });
  if (!news) {
    global.errs.AuthFailed("收藏失败");
  }
  fav_num(news_id);
  ctx.body = { code: 200, msg: "收藏成功" };
});

module.exports = router;
